﻿using System.Collections.Generic;
using System.Speech.Synthesis;
using System.Threading;
using System.Threading.Tasks;

namespace HY.Common
{
    /// <summary>
    /// 语音播报帮助类
    /// </summary>
    public static class VoiceHelper
    {
        static VoiceHelper()
        {
            PlayVoiceTask();
        }

        /// <summary>
        /// 添加播报语音
        /// </summary>
        /// <param name="msg"></param>
        public static void Play(string msg)
        {
            if (!VoiceList.Contains(msg)) VoiceList.Add(msg);
        }

        /// <summary>
        /// 语速，-10到10之间，默认0
        /// </summary>
        static int VoiceRate { get; set; } = 0;
        /// <summary>
        /// 音量，0-100
        /// </summary>
        static int VoiceVolume { get; set; } = 100;
        /// <summary>
        /// 播放语音
        /// </summary>
        /// <param name="strVoice"></param>
        static void PlayVoice(string strVoice)
        {
            SpeechSynthesizer speak = new SpeechSynthesizer();
            speak.Rate = VoiceRate;  //语速
            speak.Volume = VoiceVolume;  //音量
            //同步朗读
            speak.Speak(strVoice);
            speak.SetOutputToNull();
            speak.Dispose();  //释放之前的资源
            //异步朗读
            //speak.SpeakAsync(strVoice);
        }

        /// <summary>
        /// 需要播报的语音列表
        /// </summary>
        private static List<string> VoiceList = new List<string>();

        /// <summary>
        /// 语音线程
        /// </summary>
        private static void PlayVoiceTask()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    if (VoiceList.Count > 0)
                    {
                        foreach (string item in VoiceList.ToArray())
                        {
                            VoiceList.Remove(item);
                            PlayVoice(item);
                        }
                    }
                    else
                        Thread.Sleep(1000);
                }
            });
        }
    }
}
